package com.inphase.test.tables.daos.impl;

import com.inphase.test.tables.SysOss;
import com.inphase.test.tables.daos.BaseDao;
import org.jooq.*;
import org.jooq.impl.DAOImpl;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.ObjectProvider;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

import static org.jooq.impl.DSL.condition;


public abstract class JooqDAOImpl<R extends UpdatableRecord<R>,P> extends DAOImpl<R,P,Long> implements BaseDao<P> {

    protected final  DSLContext context;
    protected final ModelMapper modelMapper;

    protected JooqDAOImpl(Table<R> table, Class<P> type, DSLContext context,ModelMapper modelMapper) {
        super(table, type, context.configuration());
        this.context = context;
        this.modelMapper = modelMapper;
    }

    protected Long getId(com.inphase.test.tables.pojos.SysOss object) {
        return object.getId();
    }



    public List<P> selectByExample(P p) {
        return    selectByExample(p,getType());
    }

    @Override
    public <E> List<E> selectByExample(P p, Class<E> type) {
        Result<R> result = featchExample(p);

        return result.into(type);
    }


    protected   Result<R>  featchExample(P example){
        R r = context.newRecord(getTable(),example);

        Result<R> result = context.selectFrom(getTable()).where(condition(r)).fetch();
        return result;
    }



    @Override
    public void insert(Collection<P> objects) {
        beforeInsert(Optional.of(objects));
        super.insert(objects);
    }

    public void beforeInsert(P e){

    }

    private void beforeInsert( Optional<Collection<P>> objects){
        if(objects.isPresent()){
            objects.get().stream().forEach(object->{
                beforeInsert(object);
            });
        }
    }

    class CommonField{
        LocalDateTime createDate = LocalDateTime.now();

        public LocalDateTime getCreateDate() {
            return createDate;
        }

        public void setCreateDate(LocalDateTime createDate) {
            this.createDate = createDate;
        }
    }

}
